import type {
  FamilyMemberResponse,
  FamilyMemberCreate,
  FamilyMemberUpdate,
  FamilyMemberListParams,
} from "@/types/family";

import { API_BASE_URL } from "./api";

// 基础API配置
const apiConfig = {
  baseURL: `${API_BASE_URL}/api/v1`,
  headers: {
    "Content-Type": "application/json",
  },
};

// 获取认证头
function getAuthHeaders(): Record<string, string> {
  const token = localStorage.getItem("access_token");
  return token ? { Authorization: `Bearer ${token}` } : {};
}

// 处理API响应
async function handleResponse<T>(response: Response): Promise<T> {
  if (!response.ok) {
    const errorData = await response.json().catch(() => ({}));
    throw new Error(
      errorData.detail || `HTTP error! status: ${response.status}`,
    );
  }
  return response.json();
}

// 家庭成员管理API
export const familyMemberApi = {
  // 获取家庭成员列表
  async getFamilyMembers(
    params?: FamilyMemberListParams,
  ): Promise<FamilyMemberResponse[]> {
    const searchParams = new URLSearchParams();
    if (params?.skip !== undefined)
      searchParams.append("skip", params.skip.toString());
    if (params?.limit !== undefined)
      searchParams.append("limit", params.limit.toString());
    if (params?.role) searchParams.append("role", params.role);

    const response = await fetch(
      `${apiConfig.baseURL}/family-members?${searchParams.toString()}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<FamilyMemberResponse[]>(response);
  },

  // 获取单个家庭成员
  async getFamilyMember(memberId: number): Promise<FamilyMemberResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/family-members/${memberId}`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<FamilyMemberResponse>(response);
  },

  // 创建家庭成员
  async createFamilyMember(
    member: FamilyMemberCreate,
  ): Promise<FamilyMemberResponse> {
    const response = await fetch(`${apiConfig.baseURL}/family-members`, {
      method: "POST",
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
      body: JSON.stringify(member),
    });

    return handleResponse<FamilyMemberResponse>(response);
  },

  // 更新家庭成员
  async updateFamilyMember(
    memberId: number,
    member: FamilyMemberUpdate,
  ): Promise<FamilyMemberResponse> {
    const response = await fetch(
      `${apiConfig.baseURL}/family-members/${memberId}`,
      {
        method: "PUT",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
        body: JSON.stringify(member),
      },
    );

    return handleResponse<FamilyMemberResponse>(response);
  },

  // 删除家庭成员
  async deleteFamilyMember(memberId: number): Promise<void> {
    const response = await fetch(
      `${apiConfig.baseURL}/family-members/${memberId}`,
      {
        method: "DELETE",
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<void>(response);
  },

  // 检查是否为管理员
  async checkIsAdmin(memberId: number): Promise<{ is_admin: boolean }> {
    const response = await fetch(
      `${apiConfig.baseURL}/family-members/${memberId}/is-admin`,
      {
        headers: {
          ...apiConfig.headers,
          ...getAuthHeaders(),
        },
      },
    );

    return handleResponse<{ is_admin: boolean }>(response);
  },

  // 获取家庭管理员列表
  async getFamilyAdmins(): Promise<FamilyMemberResponse[]> {
    const response = await fetch(`${apiConfig.baseURL}/families/admins`, {
      headers: {
        ...apiConfig.headers,
        ...getAuthHeaders(),
      },
    });

    return handleResponse<FamilyMemberResponse[]>(response);
  },
};
